package com.srwl.mytx.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Transfer;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.service.AliService;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.Utils;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 提现详情页面
 * 提现用户可见
 */
public class WithdrawDetailActivity extends BaseActivity {
    public static void startActivity(Context context, String transferId) {
        context.startActivity(new Intent(context, WithdrawDetailActivity.class).putExtra("transferId", transferId));
    }

    private static final String TAG = "WithdrawDetailActivity";
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;

    @BindView(R.id.tv_amount)
    TextView tv_amount;
    @BindView(R.id.tv_account)
    TextView tv_account;
    @BindView(R.id.tv_apply_time)
    TextView tv_applyTime;
    @BindView(R.id.tv_transfer_status)
    TextView tv_transfer_status;
    @BindView(R.id.tv_id)
    TextView tv_Id;
    @BindView(R.id.tv_order_id)
    TextView tv_orderId;
    @BindView((R.id.ll_pay_complete))
    RelativeLayout ll_payComplete;
    @BindView(R.id.tv_pay_time)
    TextView tv_pay_time;
    @BindView(R.id.tv_customer_service)
    TextView tv_customerService;

    private Transfer transfer;

    private boolean isSync;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_withdraw_detail);
        ButterKnife.bind(this);
        String transferId = getIntent().getStringExtra("transferId");
        syncData(transferId);
        tv_customerService.setOnClickListener(v -> contactCustomerService());
    }

    /**
     * 在页面中展示数据
     */
    private void setViewAndEvent() {

        tv_amount.setText(Utils.moneyFormat(transfer.getAmount()));
        tv_account.setText(transfer.getAliAccount());
        tv_Id.setText(transfer.getId());
        tv_applyTime.setText(DateUtils.dateToString(transfer.getCreateDate(), DateUtils.FORMAT_TIMESTAMP));

        switch (transfer.getStatus()) {

            case Constant.ORDER_TRANSFER_APPLY_STATUS:
                tv_transfer_status.setText("申请提现");
                ll_payComplete.setVisibility(View.GONE);
                break;
            case Constant.ORDER_TRANSFER_SUCCESS_STATUS:
                tv_transfer_status.setText("提现成功");
                ll_payComplete.setVisibility(View.VISIBLE);
                tv_orderId.setText(transfer.getOrderId());
                tv_pay_time.setText(DateUtils.dateToString(transfer.getPayDate(), DateUtils.FORMAT_TIMESTAMP));
                break;
            case Constant.ORDER_TRANSFER_ERROR_STATUS:
                tv_transfer_status.setText("异常提现订单,请联系客服");
                ll_payComplete.setVisibility(View.VISIBLE);
                tv_pay_time.setText(DateUtils.dateToString(transfer.getPayDate(), DateUtils.FORMAT_TIMESTAMP));
                break;
        }
    }


    private void syncData(String transferId) {
        if (isSync) {
            return;
        }
        isSync = true;
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(AliService.class)
                .getTransferInfo(transferId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        isSync = false;
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        Log.d(TAG, "onResponse: 同步信息完成");
                        JSONObject body = (JSONObject) result.getData();
                        if (body == null) {
                            return;
                        }
                        transfer = body.toJavaObject(Transfer.class);
                        setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TRANSFER, transfer));
                        setViewAndEvent();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        isSync = false;
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    /**
     * 联系客服
     */
    void contactCustomerService() {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .customerService()
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(tv_customerService, getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.d(TAG, "onResponse: " + result.getMsg());
                            return;
                        }

                        JSONObject object = (JSONObject) result.getData();
                        //把用户作为临时联系人 保存在数据库
                        User manualUser = object.toJavaObject(User.class);
                        manualUser.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(manualUser);
                        ChatActivity.startActivity(WithdrawDetailActivity.this, manualUser);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(tv_customerService, getString(R.string.system_busy));
                    }
                });
    }


}
